import { Link } from "react-router-dom";
import "../assets/css/regiser.css";
import { register } from "../request/api";
import { Toast } from "antd-mobile";
import {useState} from 'react'
import {useNavigate} from 'react-router-dom'

export default function Register() {
  const navigate=useNavigate()
 const [user,setuser] =useState({
          phone: "",
          nickname: "",
          password: ""
 })

  function  yesRegister() {
    if (
     user.password === "" ||
      user.phone === "" ||
     user.nickname === ""
    ) {
      Toast.show({
        content: "不能为空",
      });

      return;
    }

    let str = /^1[3-9]\d{9}$/;

    if (!str.test(user.phone)) {
      Toast.show({
        content: "手机号格式不对",
      });

      return;
    }

    register(user).then((res) => {
      console.log(res);
      Toast.show({
        content: res.msg,
      });

      if (res.code === 200) {
        navigate('/login')
      }
    });
  }

  function Register(type, e) {
      setuser(
       {
        ...user,
        [type]: e.target.value,
      },
    )
  }

    return (
      
      <div>
        <header>
          <div className="top_box">
            <a href=" ">
              <span className="iconfont icon-zuojiantou"></span>
            </a>
            <h2>注册</h2>
            <div className="more">
              <a href="#">
                <span className="iconfont icon-gengduo"></span>
              </a>
              <div className="line"></div>

              <a href="#">
                <span className="iconfont icon-xiaoyuandian"></span>
              </a>
            </div>
          </div>
        </header>
        <section>
          <div>
            <img src={require("../assets/images/小u优选.png")} alt="" />
            <form>
              <input
                type="tel"
                placeholder="手机号"
                value={user.phone}
                onChange={Register.bind(this, "phone")}
              />
              <br />
              <input
                type="tel"
                placeholder="昵称"
                value={user.nickname}
                onChange={Register.bind(this, "nickname")}
              />
              <br />
              <input
                type="text"
                placeholder="密码"
                value={user.password}
                onChange={Register.bind(this, "password")}
              />
            </form>
      
            <input
              type="button"
              value="注         册"
              onClick={(e) => yesRegister(e)}
            ></input>

            <p>
              已有账号? <Link to="/login">去登录</Link>
            </p>
          </div>
        </section>
      </div>
    );
  }

